const directives = {
  'oss-image': {
    inserted: function(el, binding, vnode) {
      // 情况1：已经绑定src属性或已经在css样式中绑定backgroundImage，获取cdn实际渲染地址
      let bindValue = binding.value
      if (!bindValue) {
        let destUrl = vnode.context._getRealCdnUrl(el, binding)
        if (!destUrl) return
        if (el.tagName === 'IMG') {
          el.src = destUrl
        } else {
          el.style.backgroundImage = `url(${destUrl})`
        }
        return
      }
      if (bindValue) {
        let destUrl = vnode.context._getRealCdnUrl(el, binding)
        if (!destUrl) return
        const lazyLoadImage = function() {
          const rect = el.getBoundingClientRect()
          if (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.top <= (window.innerHeight || document.documentElement.clientHeight)
          ) {
            if (el.tagName === 'IMG') {
              el.src = destUrl
            } else {
              el.style.backgroundImage = `url(${destUrl})`
            }
            el.removeAttribute('data-src')
            window.removeEventListener('scroll', lazyLoadImage)
          }
        }
        el.setAttribute('data-src', destUrl)
        window.addEventListener('scroll', lazyLoadImage)
        lazyLoadImage()
      }
    },
    update: function(el, binding, vnode) {
      // 情况1：已经绑定src属性或已经在css样式中绑定backgroundImage，获取cdn实际渲染地址
      let bindValue = binding.value
      if (!bindValue) {
        let destUrl = vnode.context._getRealCdnUrl(el, binding)
        if (!destUrl) return
        if (el.tagName === 'IMG') {
          el.src = destUrl
        } else {
          el.style.backgroundImage = `url(${destUrl})`
        }
        return
      }
      if (bindValue) {
        let destUrl = vnode.context._getRealCdnUrl(el, binding)
        if (!destUrl) return
        const lazyLoadImage = function() {
          const rect = el.getBoundingClientRect()
          if (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.top <= (window.innerHeight || document.documentElement.clientHeight)
          ) {
            if (el.tagName === 'IMG') {
              el.src = destUrl
            } else {
              el.style.backgroundImage = `url(${destUrl})`
            }
            el.removeAttribute('data-src')
            window.removeEventListener('scroll', lazyLoadImage)
          }
        }
        el.setAttribute('data-src', destUrl)
        window.addEventListener('scroll', lazyLoadImage)
        lazyLoadImage()
      }
    }
  }
}
export default directives
